<?php

namespace app\sisome\controller;

use think\Controller;
use fast\Tree;

class Admin extends Common
{	

	public function _initialize()
    {
		parent::_initialize();
		$this->model = db('aduser');

		// 必须将结果集转换为数组
		$ruleList = collection(db('rule')->order('id', 'asc')->select());
		unset($v);
		Tree::instance()->init($ruleList);
		$this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
		$this->view->assign('ruledata', $this->rulelist);

	}

	public function index()
	{	

		$map = '';
		$aduid = session('aduid');
		if($aduid != '1'){
			$map = ['id' => $aduid];
		}
		$lists = $this->model->where($map)->order('id desc')->paginate(20);

		$this->assign('lists', $lists);
		return view();
	}

	public function edit()
	{		
		
		$admin = $this->model->find(input('id'));
		if(!$admin) $this->error('该用户不存在','admin');
		
		if ($this->request->isPost()) {
			$params = $this->request->post();
			if (strlen($params['uname']) < 5) {
				$this->error('用户名最少5位');
			}

			if ($params['pwd']) {
				if (strlen($params['pwd']) < 6) {
					$this->error(("密码最少6位"));
				}
				$params['pwd'] = md5($params['pwd']);
			} else {
				unset($params['pwd']);
			}

			if(isset($params['rules'])){
				$params['rules'] = implode(',', $params['rules']);
			}
			
			unset($params['__token__']);
			$result =$this->model->update($params);
			if ($result === false) {
				$this->error('修改失败');
			}

			$this->success('修改成功','index');
		}



		$rules = array();
		if($admin['rules']){
			$admin['rules'] = explode(',', $admin['rules']);
			foreach($admin['rules'] as  $k => $v){
				$rules[$v] = $v;
			}
		}
		$this->assign('rules',$rules);
		$this->assign('admin',$admin);
		
		return view();
	
	}

	// 添加
	public function add()
	{	

		if ($this->request->isPost()) {

            $params = $this->request->post();
            if ($params) {
				if (strlen($params['uname']) < 5) {
                    $this->error('用户名最少5位');
                }
                if (strlen($params['pwd']) < 6) {
                    $this->error('密码最少6位');
                }
				$params['pwd'] = md5($params['pwd']);
				$params['regip'] = $this->request->ip();
				$params['regtime'] = time();
				unset($params['__token__']);
				$count = $this->model->where('uname',$params['uname'])->count();
				if($count) $this->error('该用户已存在');
                $result = $this->model->insert($params);
                if ($result === false) {
                    $this->error('修改失败');
                }
              
            }
			$this->success('添加成功','index');
        }
        return $this->view->fetch();
	}
	
}
